const { src, dest, parallel, series, watch } = require('gulp');
const del = require('del');
// 自动加载插件
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins();
const browserSync = require('browser-sync');
const eslint = require('gulp-eslint');
const rsync = require('gulp-rsync');


const bs = browserSync.create();
const clean = () => {
  return del(['dist', 'temp'])
}
// 样式编译
const style = () => {
  return src('./src/assets/styles/*.scss', {base: 'src'})
    .pipe(plugins.sass({outputStyle: 'expanded'}))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 脚本编译
// 注意：babel一定要加 {presets: ['@babel/preset-env']} 配置参数，否则转换不生效
const script = () => {
  return src('./src/assets/scripts/*.js', {base: 'src'})
    .pipe(plugins.babel({presets: ['@babel/preset-env']}))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))

}

const lint = () => {
  return src('./src/assets/scripts/*.js', {base: 'src'})
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(dest('dist'))
    .pipe(bs.reload({ stream: true }))
}
// 页面模板编译
// swig参数，防止模板缓存导致页面不能及时更新
const page = () => {
  return src('src/*.html')
    // .pipe(plugins.swig({data}))
    .pipe(plugins.swig({ data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}
const data = {
  menus: [
    {
      name: 'Home',
      icon: 'aperture',
      link: 'index.html'
    },
    {
      name: 'Features',
      link: 'features.html'
    },
    {
      name: 'About',
      link: 'about.html'
    },
    {
      name: 'Contact',
      link: '#',
      children: [
        {
          name: 'Twitter',
          link: 'https://twitter.com/w_zce'
        },
        {
          name: 'About',
          link: 'https://weibo.com/zceme'
        },
        {
          name: 'divider'
        },
        {
          name: 'About',
          link: 'https://github.com/zce'
        }
      ]
    }
  ],
  pkg: require('./package.json'),
  date: new Date()
}

// 图片和字体文件转换
const image = () => {
  return src('src/assets/images/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
/*
imagemin字体没问题，是OK的。
*/
const font = () => {
  return src('src/assets/fonts/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 其他文件及大文件的清除
// 拷贝文件
const extra = () => {
  return src('public/**', { base: 'public'})
    .pipe(dest('dist'))
}

/*
routes: {
  '/node_modules': 'node_modules'
}
使用路由的方式处理/node_modules下面的文件的问题
*/
const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  // watch('src/assets/fonts/**', font)
  // watch('public/**', extra)

  //静态资源变化后，重新刷新浏览器，不需要重新执行构建任务
  watch([
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload)
 
  bs.init({
    notify: false,
    port: 4001,
    // open: false,
    // files: 'dist/**',
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

// useref处理打包之后的dist文件
const useref = () => {
  return src('temp/*.html', {base: 'temp'})
    .pipe(plugins.useref({ searchPath: ['temp', '.']}))
    // html js css 分别处理（useref插件）
    // 文件压缩插件 gulp-htmlmin gulp-uglify
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true,
    })))
    .pipe(dest('dist'))
}

//这几个可以同时执行，使用parallel合并
const compile = parallel(style, script, page);

// series: 按顺序执行
const build = series(
  clean, 
  parallel(
    series(compile, useref), 
    font, 
    extra
  )
);

const deploy = () => {
  return src('build/**', { base: 'build'})
  .pipe(rsync({
    root: 'build/',
    hostname: 'example.com',
    destination: 'path/to/site/',
    archive: true,
    silent: false,
    compress: true
  }))
}

//开发阶段构建任务
const start = series(compile, serve);

module.exports = {
  clean,
  build,
  serve,
  start,
  lint,
  deploy
}